$(document).ready(function() {
  initSwitchNode('cleaner')
  watchSwitchNode('cleaner')

  initSwitchNode('domain')
  watchSwitchNode('domain')

  watchDomainListNode()
  watchDomainBtnNode()
  renderDomainListNode()
})

function initSwitchNode(field) {
  getSwitchStorage(function(items) {
    const { switchStorageKey } = pickSwitch(field)
    const status = items[`${switchStorageKey}`]

    toggleSwitchNode(field, status)
  })
}

function watchSwitchNode(field) {
  const { switchNode } = pickSwitch(field)

  switchNode.on('click', function () {
    const status = switchNode.is(':checked')

    toggleSwitchNode(field, status)
  })
}

function toggleSwitchNode(field, status) {
  const { switchNode, switchTextNode } = pickSwitch(field)

  switchNode.attr('checked', status)

  switchTextNode.text(`已${status ? '开启' : '关闭'}`)

  setSwitchStorage(field, status)

  if (field === 'cleaner') {
    toggleChromeIcon(status)
  }

  else if (field === 'domain') {
    toggleDomainContainer(status)
  }
}

function getSwitchStorage(cb) {
  chrome.storage.sync.get({
    // 读取key，不存在则设置默认值,
    isOpenCleaner: true,
    isOpenDomain: false
  }, function (items) {
    cb && cb(items)
  })
}

function setSwitchStorage(field, status) {
  const { switchStorageKey } = pickSwitch(field)
  chrome.storage.sync.set({
    [switchStorageKey]: status
  })
}

function toggleChromeIcon(status) {
  chrome.action.setIcon({
    path: status ? '../images/logo.png' : '../images/logo-gray.png'
  })
}

function toggleDomainContainer(status) {
  $('#domain-container').css({
    display: status ? 'block' : 'none'
  })
}

function pickSwitch(field) {
  let switchNode, switchTextNode, switchStorageKey
  if (field === 'cleaner') {
    switchNode = $('#cleaner-switch')
    switchTextNode = $('#cleaner-switch-text')
    switchStorageKey = 'isOpenCleaner'
  } else if (field === 'domain') {
    switchNode = $('#domain-switch')
    switchTextNode = $('#domain-switch-text')
    switchStorageKey = 'isOpenDomain'
  }

  return {
    switchNode,
    switchTextNode,
    switchStorageKey
  }
}

function watchDomainBtnNode() {
  $('#domain-btn').on('click', function() {
    const inputNode = $('#domain-input')
    const inputValue = inputNode.val()

    if (!inputValue) return

    getDomainListStorage(function (items) {
      const { domainList } = items

      domainList.push({
        url: inputValue,
        is_open: true
      })

      setDomainListStorage(domainList)

      renderDomainListNode()

      inputNode.val('')
    })
  })
}

function watchDomainListNode() {
  $('#domain-list').on('click', '.btn-open', function() {
    const index = $(this).data('index')

    getDomainListStorage(function (items) {
      const { domainList } = items

      domainList[index].is_open = !domainList[index].is_open

      setDomainListStorage(domainList)

      renderDomainListNode()
    })
  })

  $('#domain-list').on('click', '.btn-delete', function () {
    const index = $(this).data('index')

    getDomainListStorage(function (items) {
      const { domainList } = items

      domainList.splice(index, 1)

      setDomainListStorage(domainList)

      renderDomainListNode()
    })
  })
}

function renderDomainListNode() {
  getDomainListStorage(function (items) {
    const { domainList } = items

    let domainItemNode = ''

    for (let i = 0; i < domainList.length; i++) {
      const {
        url,
        is_open
      } = domainList[i]

      domainItemNode += `<div class="domain-list-item">
                          <p class="url">
                            <span class="dot ${is_open ? '' : 'dot-stop'}"></span>
                            ${url}
                          </p>
                          <div class="operations">
                            <div class="btn btn-open" data-index="${i}">
                              <img src="${is_open ? '../images/start.png' : '../images/stop.png'}" class="icon" />
                            </div>
                            <div class="btn btn-delete" data-index="${i}">
                              <img src="../images/delete.png" class="icon" />
                            </div>
                          </div>
                        </div>`
    }

    $('#domain-list').html(domainItemNode)
  })
}

function getDomainListStorage(cb) {
  chrome.storage.sync.get({
    domainList: []
  }, function (items) {
    cb && cb(items)
  })
}

function setDomainListStorage(data) {
  chrome.storage.sync.set({
    domainList: data
  })
}